import { useEffect, useRef, useCallback } from 'react'

interface UseVirtualScrollOptions {
  onLoadMore: () => void
  threshold?: number
  disabled?: boolean
}

export function useVirtualScroll({
  onLoadMore,
  threshold = 100,
  disabled = false,
}: UseVirtualScrollOptions) {
  const containerRef = useRef<HTMLDivElement>(null)
  const observerRef = useRef<IntersectionObserver>()

  const handleObserver = useCallback(
    (entries: IntersectionObserverEntry[]) => {
      const target = entries[0]
      if (target.isIntersecting && !disabled) {
        onLoadMore()
      }
    },
    [onLoadMore, disabled]
  )

  useEffect(() => {
    if (disabled) return

    const observer = new IntersectionObserver(handleObserver, {
      root: null,
      rootMargin: `${threshold}px`,
      threshold: 0.1,
    })

    observerRef.current = observer

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect()
      }
    }
  }, [handleObserver, disabled])

  useEffect(() => {
    if (!containerRef.current || disabled) return

    const currentObserver = observerRef.current
    if (currentObserver) {
      currentObserver.observe(containerRef.current)
    }

    return () => {
      if (currentObserver && containerRef.current) {
        currentObserver.unobserve(containerRef.current)
      }
    }
  }, [disabled])

  return { containerRef }
}
